/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proteusadm;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Gui
 */
public class FrameVendaProd extends javax.swing.JFrame {

    private DefaultTableModel jtable1;
    private ArrayList<Produto> produtos = new ArrayList();
    private JanelaPrincipal referencia;
    private double total;
    private DecimalFormat dec = new DecimalFormat("0.00");

    /**
     * Creates new form FrameVendaProd
     */
    public FrameVendaProd() {
        initComponents();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public FrameVendaProd(JanelaPrincipal referencia) {
        initComponents();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.referencia = referencia;
        this.total = 0;
        jtable1 = (DefaultTableModel) jTable1.getModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel15 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel15.setBackground(new java.awt.Color(204, 0, 0));
        jPanel15.setEnabled(false);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Cliente :");

        jTextField4.setEditable(false);
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        jTextField4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField4KeyReleased(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton1.setText("Adicionar Cliente");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButton1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jButton1KeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
        jPanel15.setLayout(jPanel15Layout);
        jPanel15Layout.setHorizontalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(15, 15, 15))
        );
        jPanel15Layout.setVerticalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Descrição", "Preço Unitario", "Nº Unidades", "Preço"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(3);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(150);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(5);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(5);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(5);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Total R$");

        jTextField1.setEditable(false);

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton2.setText("Finalizar Venda");

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton3.setText("Adicionar despesa extra");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jTextField4KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField4KeyReleased
    }//GEN-LAST:event_jTextField4KeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        AddCliente janela = new AddCliente(this);

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            jButton1ActionPerformed(null);
        }
    }//GEN-LAST:event_jButton1KeyPressed

    private void jButton1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1KeyReleased
   }//GEN-LAST:event_jButton1KeyReleased

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_SPACE && jTable1.getRowCount() > 0) {
            opcoesTabela();
        } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
            int retorno = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir todos os produtos desta venda ?", "Excluir produtos da venda", JOptionPane.WARNING_MESSAGE);
            if (retorno == JOptionPane.OK_OPTION) {
                jtable1.setNumRows(0);
                total = 0;
                jTextField1.setText(dec.format(total));

            }
        }
    }//GEN-LAST:event_jTable1KeyPressed

    public void opcoesTabela() {
        DefaultTableModel jtable1 = (DefaultTableModel) jTable1.getModel();



////            double preco = 0;
//            try {
////                preco = Double.parseDouble((String)jTable1.getValueAt(jTable1.getSelectedRow(), 2));
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//                JOptionPane.showMessageDialog(this, "Desculpe ocorreu um erro e a tabela precisa ser fechada.");
////                jtable1 = (DefaultTableModel) jTable1.getModel();
////                jtable1.setNumRows(0);
//            }
        Object[] opcoes = {"Alterar a quantidade deste item", "Dar desconto neste item", "Excluir este produto desta venda"};
        String retorno = (String) JOptionPane.showInputDialog(this, "Escolha uma ação :", "Escolha uma opção a fazer :", 3, null, opcoes, opcoes[0]);

        // EXCLUI O PRODUTO
        if (retorno.equalsIgnoreCase("Excluir este produto desta venda")) {

            double totalitem = Double.parseDouble("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3)) * Double.parseDouble(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 2)).replaceAll(",", "."));

            total += totalitem - Double.parseDouble(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 4)).replaceAll(",", "."));

            total -= totalitem;

            produtos.remove(jTable1.getSelectedRow());
            jtable1.removeRow(jTable1.getSelectedRow());
            jTextField1.setText(dec.format(total));

            // ALTERA A QUANTIDADE DO PRODUTO
        } else if (retorno.equalsIgnoreCase("Alterar a quantidade deste item")) {
            ArrayList qtd = new ArrayList();
            int row = jTable1.getSelectedRow();
            for (int i = 1; i <= produtos.get(row).getQtd(); i++) {
                qtd.add(i);
            }
            Object[] qtd2 = qtd.toArray();
            String q = "" + JOptionPane.showInputDialog(this, "Escolha uma quantidade :", "Escolha uma quantidade :", JOptionPane.QUESTION_MESSAGE, null, qtd2, qtd2[0]);
//                Anula qual alteração de quantidade ja feito no valor total e divide o desconto pelo 
//                numero de unidades para chegar ao desconto por unidade
            double desconto = ((produtos.get(jTable1.getSelectedRow()).getPreco_v()) * Integer.parseInt(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3)))) - Double.parseDouble(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 4)).replaceAll(",", "."));

            if (desconto != 0) {
                desconto = desconto / Integer.parseInt("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3));
            }

            total += desconto * Integer.parseInt(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3)));
            total -= Double.parseDouble("" + jTable1.getValueAt(row, 3)) * produtos.get(row).getPreco_v();

            int quant = Integer.parseInt(q);

            jTable1.setValueAt(quant, row, 3);

            double valor = quant * (Double.parseDouble(("" + jTable1.getValueAt(row, 2)).replaceAll(",", ".")));

            double desconto_final = desconto * quant;

            jTable1.setValueAt(dec.format(valor - desconto_final), row, 4);
            total += valor - desconto_final;
            jTextField1.setText(dec.format(total));


//                DA DESCONTO NO PRODUTO
        } else if (retorno.equalsIgnoreCase("Dar Desconto neste item")) {

//                JPasswordField password = new JPasswordField(10);
//                password.setEchoChar('*');
//                JLabel label2 = new JLabel("Digite sua senha :");
//                JPanel container = new JPanel();
//                container.add(label2);
//                container.add(password);
//                JOptionPane.showMessageDialog(this, container, "Acesso restrito ao administrador", 1);
//                JOptionPane.showMessageDialog(this, password.getText());
//                if (Banco.isTruePassword(password.getText())) {
//                    JOptionPane.showMessageDialog(this, "Ok");

            Object[] op = {"0 %", "5 %", "10 %", "15 %", "20 %", "25 %", "30 %", "35 %", "40 %", "45 %", "50 %", "60 %", "70 %", "80 %", "90 %", "100 %"};
            String r = "" + JOptionPane.showInputDialog(this, "Escolha um desconto :", "Escolha um valor de desconto :", JOptionPane.QUESTION_MESSAGE, null, op, op[0]);
            double valor = Double.parseDouble(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 2)).replaceAll(",", "."));
//                Anula algum possivel desconto ja dado. para o valor total
//                pega o (preço unitario do produto * quantidade) - o preco total do item
            total += ((produtos.get(jTable1.getSelectedRow()).getPreco_v()) * Integer.parseInt(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3)))) - Double.parseDouble(("" + jTable1.getValueAt(jTable1.getSelectedRow(), 4)).replaceAll(",", "."));
            double desconto = 0;
            if (valor != 0) {
                desconto = (valor * (Double.parseDouble(r.replaceAll("%", "").trim()) / 100)) * Integer.parseInt("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3));
            }
//                pega o valor unitario do produto multiplica pelo desconto (porcentagem) e depois multiplica pela quantidade de itens
            total -= desconto;
//                pega o valor do unitario do produto multiplica pela quantidade e subtrai o desconto
            jTable1.setValueAt(dec.format(((produtos.get(jTable1.getSelectedRow()).getPreco_v()) * Integer.parseInt("" + jTable1.getValueAt(jTable1.getSelectedRow(), 3))) - desconto), jTable1.getSelectedRow(), 4);
            jTextField1.setText(dec.format(total));

//                } else {
//                    JOptionPane.showMessageDialog(this, "Fail autentication");
//                }


        }
        }

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        referencia.atualizaFrameVendas();
        this.dispose();

        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosing

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        FrameDespesaExtra frame = new FrameDespesaExtra(this);


        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getButton() == MouseEvent.BUTTON3) {
            opcoesTabela();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    public void addProdutos(Produto p, int qtd) {

        boolean onList = false;
        for (int i = 0; i < produtos.size(); i++) {
            if (p.getCodigo() == produtos.get(i).getCodigo() && p.getCodigo() != 0) {
                onList = true;
                break;
            }
        }

        if (!onList) {
            Object[] dados = {"" + p.getCodigo(), p.getDescricao(), "" + p.getPreco_v(), qtd, "" + dec.format(p.getPreco_v() * qtd)};
            jtable1.addRow(dados);
            produtos.add(p);
            total += qtd * p.getPreco_v();
            jTextField1.setText(dec.format(total));
        } else {
            JOptionPane.showMessageDialog(this, "O item já está adicionado a lista (produto codigo = " + p.getCodigo() + ")\nPor favor altere sua quantidade se for o caso.");
        }
    }

    public void setJTextFieldCliente(String retorno) {
        jTextField4.setText(retorno);
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(FrameVendaProd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(FrameVendaProd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(FrameVendaProd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(FrameVendaProd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the form
//         */
////        java.awt.EventQueue.invokeLater(new Runnable() {
////
////            public void run() {
////                new FrameVendaProd().setVisible(true);
////            }
////        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
}
